# @Time : 2020/8/28 17:21
# @Author : Fioman 
# @Phone : 13149920693
"""
使用轮廓的高级特性,识别井字游戏上的圆圈和××
"""
import cv2 as cv
import numpy as np
import imutils

image = cv.imread("pic/20.png")
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cnts = cv.findContours(gray.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

clone = image.copy()
for index, c in enumerate(cnts):
    char = "?"
    area = cv.contourArea(c)
    x, y, w, h = cv.boundingRect(c)

    hull = cv.convexHull(c)
    hullArea = cv.contourArea(hull)
    solidity = area / hullArea
    if solidity > 0.9:
        cv.drawContours(clone, [c], -1, (0, 255, 0), 2)
    elif solidity > 0.5:
        cv.drawContours(clone, [c], -1, (0, 0, 255), 2)

    if solidity > 0.9:
        char = "O"
    elif solidity > 0.5:
        char = "X"

    if char != "?":
        cv.drawContours(image, [c], -1, (0, 255, 0), 3)
        cv.putText(image, char, (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 1.25, (0, 255, 0), 4)
cv.imshow("Contours", clone)
cv.imshow("Contours2", image)
cv.waitKey(0)
cv.destroyAllWindows()

image = cv.imread("pic/21.png")
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

cnts = cv.findContours(gray.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

clone = image.copy()
for index, c in enumerate(cnts):
    M = cv.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    cv.putText(clone, "# {}".format(index + 1), (cX - 10, cY), cv.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 4)
    x, y, w, h = cv.boundingRect(c)
    print("# {} aspect ratio = {}".format(index + 1, w / h))

    area = cv.contourArea(c)
    hull = cv.convexHull(c)
    hullArea = cv.contourArea(hull)
    print("# {} solidity = {}".format(index + 1, area / hullArea))

    print("# {} extend = {}".format(index + 1, area / (w * h)))

cv.imshow("Clone", clone)
cv.waitKey(0)
